﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;

namespace JoyeriaProject
{
    public partial class frmPayment : Form
    {
        public int CustomerID;
        
        private ModeloDatos MD = new ModeloDatos();
        
        public frmPayment()
        {
            InitializeComponent();
        }

        private void frmPayment_Load(object sender, EventArgs e)
        {
            dateTimePick.Value = DateTime.Now; 

            foreach (Agentes agente in MD.GetAgents())
                comboAgente.Items.Add(agente.Nombre + " " + agente.Apellidos);
                
            txtAmount.Focus();
        }

        private void btnCancelar_Click(object sender, EventArgs e)
        {
            Dispose();
        }

        private void btnGuardar_Click(object sender, EventArgs e)
        {
            double Num = 0;

            if (txtAmount.Text != string.Empty && double.TryParse(txtAmount.Text, out Num) && comboAgente.SelectedItem != null)
            {
                double saldo = 0;
                
                foreach (var Element in MD.GetComprasPagos().GroupBy(n => n.CustomerID).Where(ff => ff.Key == CustomerID).Select(g => new { Result = g.Sum(p => p.Cargo) - g.Sum(p => p.Abono) }))
                    saldo = Element.Result - Convert.ToDouble(txtAmount.Text);
            
                MD.PaymentShopping = new ComprasPagos
                {
                    ID = System.Guid.NewGuid().ToString(),
                    CustomerID = CustomerID,
                    Fecha = dateTimePick.Value.Month.ToString("00") + dateTimePick.Value.Day.ToString("00") + dateTimePick.Value.Year.ToString("0000"),
                    Date = dateTimePick.Value,
                    Cargo = 0,
                    Abono = Convert.ToDouble(txtAmount.Text),
                    Saldo = saldo,
                    Articulo = "",
                    Firma = comboAgente.SelectedItem.ToString()
                };
                
                    
                if (MD.Add<ComprasPagos>(ref MD.PaymentShopping))
                {
                    MessageBox.Show("El pago se Registro Satisfactoriamente", "LISTO!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Dispose();
                }
                else
                {
                    MessageBox.Show("Hubo un problema al grabar el registro del Pago", ":(  HUBO UN PROBLEMA", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }
            else 
            {
                MessageBox.Show( comboAgente.SelectedItem == null ? "Selecciona un Cobrador" : "Coloca o Corrije el Monto a pagar", "ESPERA", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

        }

    }
}
